<template>
  <div>
    <div style="margin-bottom: 20px;">
      <el-button v-if="hasPermission('/system/resources/add')"
        type="primary" 
        @click="addResource"
        style="margin-right: 10px;"
      >
        添加资源
      </el-button>
      <el-button v-if="hasPermission('/system/resources/update')"
        @click="editResource"
        style="margin-right: 10px;"
      >
        编辑资源
      </el-button>
      <el-button @click="deleteResource" v-if="hasPermission('/system/resources/delete')">
        删除资源
      </el-button>
    </div>
    <el-tree
      :data="treeData"
      :default-expanded-keys="defaultExpandedKeys"
      :props="defaultProps"
      ref="resourceTree"
      node-key="id"
      :render-content="renderContent"
      @node-click="handleNodeClick"
      :highlight-current="true"
      style="max-height: 500px; overflow-y: auto;"
    />
  </div>
</template>

<script>
import { getResourcesList, deleteResources } from '@/api/resources'
import { hasPermission } from '@/utils/permissions'

export default {
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'text'
      },
      selectedNode: null,
      defaultExpandedKeys: [/* 默认展开的节点ID */]
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      try {
        const { data } = await getResourcesList()
        this.treeData = data.data
      } catch (error) {
        console.error('获取资源列表失败:', error)
        this.$message.error('获取资源列表失败')
      }
    },
    addResource() {
      if (this.selectedNode) {
        this.$router.push(`/resources/add/${this.selectedNode.id}`)
      } else {
        this.$message.warning('请先选择一个资源节点')
      }
    },
    editResource() {
      if (this.selectedNode) {
        this.$router.push(`/resources/edit/${this.selectedNode.id}`)
      } else {
        this.$message.warning('请先选择一个资源节点')
      }
    },
    async deleteResource() {
      if (this.selectedNode) {
        try {
          await this.$confirm('确认删除该资源吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          await deleteResources(this.selectedNode.id)
          this.$message.success('删除成功')
          this.fetchData()
        } catch (error) {
          if (error !== 'cancel') {
            console.error('删除资源失败:', error)
            this.$message.error('删除资源失败')
          }
        }
      } else {
        this.$message.warning('请先选择一个资源节点')
      }
    },
    handleNodeClick(node) {
      this.selectedNode = node
    },
    hasPermission(permission) {
      return hasPermission(this.$store, permission);
    }
  }
}
</script>